package com.bootdo.common.controller;/**
 * @author jafar.tang
 * @date 2018/9/5 19:56
 * @description
 */

import com.bootdo.common.config.QcloudCosConfig;
import com.bootdo.common.utils.R;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * Created on 2018/09/05.
 * Description:
 * Copyright (c) 2018, 成都冰鉴信息科技有限公司
 * All rights reserved.
 *
 * @author jafar.tang
 */
@Controller
@RequestMapping("/cos")
@Api("上传文件到COS")
public class CosController {
    private static final Logger logger = LoggerFactory.getLogger(CosController.class);

    @Autowired
    private QcloudCosConfig cosConfig;

    /**
     * 上传的单个文件
     * @param prefix
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation("上传的单个文件")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "prefix", required = false, value = "文件所在目录，仅允许一级目录", paramType = "query", defaultValue = "mobile"),
    })
    public R upload(
            @RequestParam(value = "prefix", defaultValue = "")
            String prefix,
            MultipartFile file) {

        try {
            String putObjectResult = uploadToCOS(file, prefix);
            return R.ok().put("result", cosConfig.getHost()+putObjectResult);
        }catch (IOException e) {
            logger.error("上传文件失败: "+e.getMessage(), e);
            return R.error("上传失败!").put("error", e);
        }
    }

    @PostMapping("/uploadBatch")
    @ResponseBody
    @Deprecated
    public R uploadBatch(
            @RequestParam(value = "prefix", defaultValue = "")
                    String prefix,
            MultipartFile[] file) {
        try {
            String[] urls = new String[file.length];
            for (int i = 0; i < file.length; i++) {
                MultipartFile multipartFile = file[i];
                String putObjectResult = uploadToCOS(multipartFile, prefix);
                urls[i] = putObjectResult;
            }
            return R.ok().put("result", urls);
        } catch (IOException e) {
            logger.error("上传文件失败: "+e.getMessage(), e);
            return R.error("上传失败!").put("error", e);
        }
    }

    /**
     * 上传文件
     * @param file
     * @param prefix
     * @return
     * @throws IOException
     */
    private String uploadToCOS(MultipartFile file, String prefix) throws IOException {
        File upload = File.createTempFile("upload", ".tmp");
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(upload));
        String key = getKey(prefix, file.getOriginalFilename());
        PutObjectRequest request = new PutObjectRequest(cosConfig.getBucket(), key, upload);
        PutObjectResult putObjectResult = cosConfig.getClient().putObject(request);
        return putObjectResult == null? "" : key;
    }

    /**
     * 生成上传路径
     * @param prefix
     * @param fileName
     * @return
     */
    private String getKey(final String prefix, String fileName) {
        LocalDate date = LocalDate.now();
        String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String strPrefix = StringUtils.isBlank(prefix) ? "" : prefix.replaceAll("/", "")+"/";
        String key = "/upload/"+ strPrefix
                +date.toString()+"/"+ UUID.randomUUID()+ext;
        return key;
    }

    @GetMapping
    @Deprecated
    public String index() {
        return "test/upload.html";
    }


}
